<template>
  <div style="overflow-x: auto; justify-content: center; align-items: center; height: 100%;">
    <div class="daysClass">
      <label>请输入天数：</label>
      <vxe-input type="text" v-model="days" placeholder="请输入天数"
                 @blur="searchFunction"
                 @keyup.enter.native="searchFunction"
      >请输入天数</vxe-input>
    </div>
    <div id="myEChartsLine" ref="lineChart" style="width: 100%;  height: 700px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {getMachineDetaiLine} from '@/services/DataService';


export default {
  name: 'Machine-LineChart',
  data() {
    return {
      chartData: null, // 用于存储从 API 获取的数据
      titleText:'',
      machines:{},
      days:100,
      machinename:"",
      chartInstance: null, // 用来保存 ECharts 实例的引用
      countdown: 60, // 初始倒计时时间（秒）

      count: 0,
      timerId: null,
    };
  },
  mounted () {
    document.title = this.titleText;
  },
  created() {
    // 获取查询参数
    this.machinename = this.$route.query.machinename;
    this.days = this.$route.query.days;
    this.getdataSource();
  },
  methods: {
      searchFunction() {
        this.getdataSource();
      },
      async getdataSource(){
        this.titleText = '机器【'+this.machinename+'】在'+this.days+'天内的折线图';
        try {
          this.chartData = await getMachineDetaiLine(this.days,this.machinename);
          this.initLineChart();
        } catch (error) {
          console.error('Error fetching data:', error);
        }
      },
      // 折线图的自定义提示目标
      tooltipFormatter(params) {
        const length_p = params.length;
        if (length_p==0){
          return '';
        }

        let machine = this.machines[params[0].name];
        let batchname = machine.batchname;
        let dyeprogname = machine.dyeprogname;
        let water_total_all = machine.water_total_all;
        let loading = machine.loading;

        let res = `<ul style="list-style-type: disc; padding-left: 20px;">
              <li style="text-align: left;">缸号：${batchname}/${dyeprogname}</li>`;

        for (const paramsitem of params) {
          const name = paramsitem.seriesName;
          let value = paramsitem.value;

          if (name === "在线状态") {
            value = value === '20' ? '中央' : '单机';
          } else if (name === "运行状态") {
            value = value === '10' ? '运行' : '停止';
          }else{
            if(name == "布吨耗水"){
              res += `<li style="text-align: left;">总水量：${water_total_all}；布重：${loading}</li>`;
            }
          }
          res += `<li style="text-align: left;">${name}：${value}</li>`;
        }
        res += '<ul>';
        return res;

      },
      initLineChart() {
        // 判断数据源
        if (!this.chartData) {
          console.error('Chart data is not available yet.');
          return;
        }
        //初始化实例
        if (null==this.chartInstance){
          this.chartInstance = echarts.init(this.$refs.lineChart);
        }
        //定义折线数字
        const rawData = {
          categories: [],
          dataSeries1: [],//运行状态
          dataSeries2: [],//在线状态
          dataSeries3: [],//布吨耗水
          dataSeries4: [],
        };

        this.chartData.forEach(item => {
          let runtime = item.runtime;
          rawData.categories.push(runtime);
          rawData.dataSeries1.push(item.machinestate);
          rawData.dataSeries2.push(item.machinemode);
          rawData.dataSeries3.push(item.water_loading_rate);
          rawData.dataSeries4.push(item.standard_line);

          this.machines[runtime] = {
            batchname: item.batchname,
            dyeprogname: item.dyeprogname,
            water_total_all: item.water_vol4_total_all,
            loading: item.loading
          };
        });

        const xAxisData = rawData.categories;
        // symbolSize: 0.1,//改变转折点的原点大小
        // stack: 'x', // 堆叠效果
        const seriesData = [
          {name: '运行状态',type: 'line',symbolSize: 0.1,data: rawData.dataSeries1,},
          {name: '在线状态', type: 'line',symbolSize: 0.1,data: rawData.dataSeries2,},
          {name: '布吨耗水',type: 'line',symbolSize: 0.1,data: rawData.dataSeries3,},
          {name: '布吨耗水标准线',type: 'line',symbolSize: 0.1,data: rawData.dataSeries4,},
        ];

        const option = {
          title: {
            text: this.titleText, // 设置标题文本
            left: 'left', // 标题位置，可以是 'left'、'center'、'right'
            top: '4%',
            textStyle: {
              color: '#333',
              fontSize: 20
            }
          },
          tooltip: {
            trigger: 'axis',//提示类型：'item'、'axis'
            formatter: this.tooltipFormatter,
            axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985'} }
          },
          legend: {
            top: '10%',
            left: 'left',
            data: ['运行状态','在线状态', '布吨耗水', '布吨耗水标准线']
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            name: '时刻点',
            scale: true,// 纵坐标无限延伸
            axisLabel: {
              rotate: 45// 调整标签的旋转角度、间距等，避免与标题重叠
            }
          },
          yAxis: { type: 'value' },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true, // 确保标签在grid区域内
            // 可以通过调整top的值来确保标题和数据标签之间有足够的空间
            top: '20%' // 根据标题大小调整这个值
          },
          series: seriesData
        };
        this.chartInstance.setOption(option);
    }
  },
  // 销毁之前，销毁定时任务
  beforeDestroy() {
    // if (this.timerId) {
    //   clearInterval(this.timerId);
    //   this.timerId = null;
    // }
  },
};
</script>